package com.example.backend.service;

import com.example.backend.domain.enums.TicketStatus;
import com.example.backend.domain.enums.TicketPriority;
import com.example.backend.repository.TicketRepository;
import com.example.backend.repository.FeedbackRepository;
import com.example.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计服务类
 * 提供各种数据统计功能
 */
@Service
public class StatisticsService {

    @Autowired
    private TicketRepository ticketRepository;

    @Autowired
    private FeedbackRepository feedbackRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取工单统计信息
     */
    @Cacheable(value = "tickets", key = "'stats'")
    public Map<String, Object> getTicketStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总工单数
        long totalTickets = ticketRepository.count();
        stats.put("totalTickets", totalTickets);
        
        // 按状态统计
        Map<String, Long> statusStats = new HashMap<>();
        for (TicketStatus status : TicketStatus.values()) {
            long count = ticketRepository.countByStatus(status);
            statusStats.put(status.name(), count);
        }
        stats.put("statusStats", statusStats);
        
        // 按优先级统计
        Map<String, Long> priorityStats = new HashMap<>();
        for (TicketPriority priority : TicketPriority.values()) {
            long count = ticketRepository.countByPriority(priority);
            priorityStats.put(priority.name(), count);
        }
        stats.put("priorityStats", priorityStats);
        
        // 今日新增工单
        Instant today = Instant.now().truncatedTo(ChronoUnit.DAYS);
        long todayTickets = ticketRepository.countByCreatedAtAfter(today);
        stats.put("todayTickets", todayTickets);
        
        // 本周新增工单
        Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS);
        long weekTickets = ticketRepository.countByCreatedAtAfter(weekAgo);
        stats.put("weekTickets", weekTickets);
        
        return stats;
    }

    /**
     * 获取反馈统计信息
     */
    @Cacheable(value = "feedbacks", key = "'stats'")
    public Map<String, Object> getFeedbackStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总反馈数
        long totalFeedbacks = feedbackRepository.count();
        stats.put("totalFeedbacks", totalFeedbacks);
        
        // 平均评分
        Double avgRating = feedbackRepository.getAverageRating();
        stats.put("averageRating", avgRating != null ? avgRating : 0.0);
        
        // 评分分布
        Map<String, Long> ratingDistribution = new HashMap<>();
        for (int i = 1; i <= 5; i++) {
            long count = feedbackRepository.countByRating(i);
            ratingDistribution.put(String.valueOf(i), count);
        }
        stats.put("ratingDistribution", ratingDistribution);
        
        // 满意度统计（4-5分为满意）
        long satisfiedCount = feedbackRepository.countByRatingGreaterThanEqual(4);
        long satisfactionRate = totalFeedbacks > 0 ? (satisfiedCount * 100 / totalFeedbacks) : 0;
        stats.put("satisfactionRate", satisfactionRate);
        
        return stats;
    }

    /**
     * 获取用户统计信息
     */
    @Cacheable(value = "users", key = "'stats'")
    public Map<String, Object> getUserStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 总用户数
        long totalUsers = userRepository.count();
        stats.put("totalUsers", totalUsers);
        
        // 活跃用户数（最近7天有登录）
        Instant weekAgo = Instant.now().minus(7, ChronoUnit.DAYS);
        long activeUsers = userRepository.countByLastLoginAtAfter(weekAgo);
        stats.put("activeUsers", activeUsers);
        
        return stats;
    }

    /**
     * 获取系统概览统计
     */
    public Map<String, Object> getSystemOverview() {
        Map<String, Object> overview = new HashMap<>();
        
        overview.put("tickets", getTicketStatistics());
        overview.put("feedbacks", getFeedbackStatistics());
        overview.put("users", getUserStatistics());
        
        // 系统运行时间
        overview.put("systemUptime", System.currentTimeMillis() - getSystemStartTime());
        
        return overview;
    }

    private long getSystemStartTime() {
        // 这里可以从系统属性或配置中获取启动时间
        return System.currentTimeMillis() - 86400000; // 示例：假设运行了1天
    }

    /**
     * 获取工单趋势图表数据
     */
    @Cacheable(value = "charts", key = "'ticket-trend'")
    public Map<String, Object> getTicketTrendChartData() {
        Map<String, Object> chartData = new HashMap<>();
        
        // 获取最近7天的数据
        List<String> labels = new ArrayList<>();
        List<Long> createdData = new ArrayList<>();
        List<Long> resolvedData = new ArrayList<>();
        
        LocalDate today = LocalDate.now();
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            labels.add(date.getDayOfWeek().toString().substring(0, 3)); // 简化的星期名
            
            Instant startOfDay = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
            Instant endOfDay = date.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant();
            
            // 当天创建的工单数
            long created = ticketRepository.countByCreatedAtBetween(startOfDay, endOfDay);
            createdData.add(created);
            
            // 当天解决的工单数
            long resolved = ticketRepository.countByUpdatedAtBetweenAndStatus(startOfDay, endOfDay, TicketStatus.RESOLVED);
            resolvedData.add(resolved);
        }
        
        chartData.put("labels", labels);
        chartData.put("datasets", List.of(
            Map.of(
                "label", "新建工单",
                "data", createdData,
                "borderColor", "#dc3545",
                "backgroundColor", "rgba(220, 53, 69, 0.1)"
            ),
            Map.of(
                "label", "已解决工单", 
                "data", resolvedData,
                "borderColor", "#28a745",
                "backgroundColor", "rgba(40, 167, 69, 0.1)"
            )
        ));
        
        return chartData;
    }

    /**
     * 获取工单状态分布图表数据
     */
    @Cacheable(value = "charts", key = "'ticket-status'")
    public Map<String, Object> getTicketStatusChartData() {
        Map<String, Object> chartData = new HashMap<>();
        
        List<String> labels = new ArrayList<>();
        List<Long> data = new ArrayList<>();
        List<String> colors = new ArrayList<>();
        
        // 状态映射
        Map<TicketStatus, String> statusLabels = Map.of(
            TicketStatus.OPEN, "待处理",
            TicketStatus.IN_PROGRESS, "处理中", 
            TicketStatus.RESOLVED, "已解决",
            TicketStatus.CLOSED, "已关闭"
        );
        
        Map<TicketStatus, String> statusColors = Map.of(
            TicketStatus.OPEN, "#ffc107",
            TicketStatus.IN_PROGRESS, "#17a2b8",
            TicketStatus.RESOLVED, "#28a745", 
            TicketStatus.CLOSED, "#6c757d"
        );
        
        for (TicketStatus status : TicketStatus.values()) {
            long count = ticketRepository.countByStatus(status);
            if (count > 0) { // 只显示有数据的状态
                labels.add(statusLabels.get(status));
                data.add(count);
                colors.add(statusColors.get(status));
            }
        }
        
        chartData.put("labels", labels);
        chartData.put("datasets", List.of(Map.of(
            "data", data,
            "backgroundColor", colors
        )));
        
        return chartData;
    }
}
